package com.lucy.management.config.oper;

import com.alibaba.fastjson.JSON;
import com.lucy.management.config.auth.AdminLogin;
import com.lucy.management.config.auth.AdminLoginModel;
import com.lucy.management.dao.ExceptionLogMapper;
import com.lucy.management.dao.OperationLogMapper;
import com.lucy.management.domain.ExceptionLog;
import com.lucy.management.domain.OperationLog;
import com.lucy.management.utils.AjaxResult;

import com.lucy.management.utils.IpUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 切面处理类，操作日志异常日志记录处理
 *
 * @author admin
 * @date 2020/03/09
 */
@Aspect
@Component
public class OperLogAspect extends AjaxResult {

    private static final Logger log = LogManager.getLogger(OperLogAspect.class);

    @Autowired
    OperationLogMapper operationLogMapper;

    @Autowired
    ExceptionLogMapper exceptionLogMapper;

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.lucy.management.config.oper.OperLog)")
    public void operLogPoinCut() {

    }

    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.lucy.management.controller..*.*(..))")
    public void operExceptionLogPoinCut() {
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        logRecord(joinPoint, keys, request);
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String excName = e.getClass().getName();
        //自定义异常
        if ("com.yqsh.recruitment.util.CustomException".equals(excName)) {
            Map map = new HashMap();
            map.put("code", 400);
            map.put("flag", false);
            map.put("msg", e.getMessage());
            logRecord(joinPoint, map, request);
        } else {
            ExceptionLog excepLog = new ExceptionLog();
            try {
                // 从切面织入点处通过反射机制获取织入点处的方法
                MethodSignature signature = (MethodSignature) joinPoint.getSignature();
                // 获取切入点所在的方法
                Method method = signature.getMethod();
                // 获取请求的类名
                String className = joinPoint.getTarget().getClass().getName();
                // 获取请求的方法名
                String methodName = method.getName();
                methodName = className + "." + methodName;
                // 获取操作
                OperLog opLog = method.getAnnotation(OperLog.class);
                if (opLog != null) {
                    String operDesc = opLog.operDesc();
                    excepLog.setOperDesc(operDesc); // 操作描述
                }
                // 请求的参数
                Map<String, String> rtnMap = converMap(request.getParameterMap());
                // 将参数所在的数组转换成json
                String params = JSON.toJSONString(rtnMap);
                excepLog.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                excepLog.setOperRequParam(params); // 请求参数
                excepLog.setOperMethod(methodName); // 请求方法名
                excepLog.setExcName(e.getClass().getName()); // 异常名称
                excepLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 异常信息
                //获取当前用户
                AdminLoginModel loginModel = AdminLogin.getAdminLoginModel(request);
                excepLog.setOperUser(loginModel.getUuid()); // 操作员ID
                excepLog.setOperUserName(loginModel.getUserName()); // 操作员名称
                excepLog.setOperUri(request.getRequestURI()); // 操作URI
                excepLog.setOperIp(IpUtil.getIpAddrByRequest(request)); // 操作员IP
                excepLog.setOperCreateTime(new Date()); // 发生异常时间
                exceptionLogMapper.insertSelective(excepLog);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
            log.error("方法描述：" + excepLog.getOperDesc() + "---请求方法：" + excepLog.getOperMethod() + "---请求参数：" + excepLog.getOperRequParam()
                    + "----异常名称：" + excepLog.getExcName() + "---异常信息：" + excepLog.getExcMessage() + "---请求IP：" + excepLog.getOperIp()
                    + "---请求URL：" + excepLog.getOperUri() + "---创建时间:" + excepLog.getOperCreateTime());
        }
    }

    /**
     * 操作日志记录
     *
     * @param joinPoint
     * @param keys
     * @param request
     */
    private void logRecord(JoinPoint joinPoint, Object keys, HttpServletRequest request) {
        OperationLog operlog = new OperationLog();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取操作
            OperLog opLog = method.getAnnotation(OperLog.class);
            if (opLog != null) {
                String operDesc = opLog.operDesc();
                operlog.setOperDesc(operDesc); // 操作描述
            }
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;

            operlog.setOperMethod(methodName); // 请求方法

            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSON.toJSONString(rtnMap);
            operlog.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            operlog.setOperRequParam(params); // 请求参数
            operlog.setOperRespParam(JSON.toJSONString(keys)); // 返回结果
            operlog.setOperIp(IpUtil.getIpAddrByRequest(request)); // 请求IP
            operlog.setOperUri(request.getRequestURI()); // 请求URI
            operlog.setOperCreateTime(new Date()); // 创建时间

            //获取当前用户
            AdminLoginModel loginModel = AdminLogin.getAdminLoginModel(request);
            operlog.setOperUser(loginModel.getUuid());
            operlog.setOperUserName(loginModel.getUserName());
            operationLogMapper.insertSelective(operlog);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        log.info("方法描述：" + operlog.getOperDesc() + "---请求方法：" + operlog.getOperMethod() + "---请求参数：" + operlog.getOperRequParam() + "----返回结果：" + operlog.getOperRespParam() + "---请求IP：" + operlog.getOperIp() + "---请求URL：" + operlog.getOperUri() + "---创建时间:" + operlog.getOperCreateTime());
    }

    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }
}